import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, convertFromHTML, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const confirm = Modal.confirm;
const { TextArea } = Input;

import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { demandReply } from '../../services/api';
import { getArrFromObj } from '../../utils/utils';
import config from '../../common/config';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import counties from '../../data/counties.json';

import styles from './highValuation.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const REPORT_STATUS_MAP = {
  '0': '暂存',
  '1': '完成',
};

const REPORT_STATUS_ARR = getArrFromObj(REPORT_STATUS_MAP);

const pageSize = 10;

@connect(({ highValuation, loading }) => {
  return {
    highValuation,
    loading: loading.models.highValuation,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    this.init();
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'highValuation/queryList',
      payload: {
        pageNum: 1,
        pageSize: pageSize,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'highValuation/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'highValuation/queryList',
      payload: {},
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (!fieldsValue.name) {
        delete fieldsValue.name;
      }

      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: pageSize,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'highValuation/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      title: '',
      editorState: EditorState.createEmpty(),
    });
  };

  async handleSave(e) {
    if (this.state.state === 1) {
      return this.setState({
        modalVisible: false,
      });
    }
    const { processDesc } = this.state;
    if (!processDesc) {
      return message.error('回复内容不能为空');
    }

    await this.doSave();
  }

  async doSave() {
    const { dispatch } = this.props;

    const { id, processDesc } = this.state;
    const params = { id, processDesc };

    const response = await demandReply(params);

    if (response.code === 200) {
      this.setState({
        modalVisible: false,
      });

      this.init();
    } else {
      message.error(response.message);
    }
  }

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  onEditorStateChange = editorState => {
    this.setState({
      editorState,
    });
  };

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('name')(<Input placeholder="企业名称" />)}
            </FormItem>
          </Col>

          <Col md={3} sm={24}>
            <FormItem label="">
              {getFieldDecorator('status')(
                <Select style={{ width: '100%' }} placeholder="测评状态">
                  {REPORT_STATUS_ARR.map(item => {
                    return (
                      <Option key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={3} sm={24}>
            <span style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleReply(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  isDatetimeDisabled() {
    if (this.state.siteNoticeType == 'SCHEDULED') {
      return false;
    }

    return true;
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  onRadioChange(e) {
    this.setState({
      siteNoticeType: e.target.value,
    });
  }

  onOk() {}

  handlePublish(item) {
    const { dispatch } = this.props;
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    let { highValuation: { data }, loading } = this.props;
    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (val, item, index) => (
          <span>{(data.pagination.current - 1) * data.pagination.pageSize + index + 1}</span>
        ),
      },
      {
        title: '企业名称',
        dataIndex: 'enterpriseName',
        render: val => <span>{val ? val : '-'}</span>,
      },
      {
        title: '处理状态',
        dataIndex: 'evalStatus',
        render: val => <span>{REPORT_STATUS_MAP[val]}</span>,
      },
      {
        title: '测评得分',
        dataIndex: 'evalScore',
      },
      {
        title: '发放时间',
        dataIndex: 'createTime',
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: '操作',
        dataIndex: 'status',
        render: (val, item) => (
          <span>
            <a href={`${config.pcSiteUrl}/evaluateqa.html?id=${item.id}`} target="_blank">
              查看
            </a>&nbsp;
            <a href={`${config.pcSiteUrl}/evaluatereport.html?id=${item.id}`} target="_blank">
              查看测评报告
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="高企测评">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>

            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          style={{ width: '800px' }}
          title={this.state.state === 0 ? '意向回复' : '回复查看'}
          visible={this.state.modalVisible}
          onOk={this.handleSave.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <DescriptionList size="large" title="" col="1">
            {this.state.state === 0 && (
              <Description term="回复内容" termStyle={styles.top}>
                <TextArea
                  rows={4}
                  value={this.state.processDesc}
                  onChange={this.handleOnchange.bind(this, 'processDesc')}
                />
                <div>注：回复内容，该会员可在“会员中心“查看！</div>
              </Description>
            )}

            {this.state.state === 1 && (
              <Description term="回复内容">{this.state.processDesc}</Description>
            )}
            {this.state.state === 1 && (
              <Description term="回复时间">{this.state.processTime}</Description>
            )}
          </DescriptionList>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
